package fr.sportsurbains.reader;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class TopicsReader {
	Connection cnx;
	Document doc;
	
	public TopicsReader (String url) throws IOException {
		cnx = Jsoup.connect(url);
		doc = cnx.timeout(10000).get();
	}
	
	public List<Map<String,String>> getTopics() {
		Elements elts = doc.getElementsByTag("article");
		List<Map<String,String>> listTopics = new ArrayList<Map<String,String>>();
		for(Element elt:elts) {
			//Log.d("TEST",elt.className());
			if(elt.id().equals("post-0")) {
				//on mode search, there is no results
				break;
			}
			String urlImage = "";
			String summary = "";
			String title = elt.getElementsByTag("header").first().getElementsByTag("h2").first().getElementsByTag("a").first().text();
			if(elt.getElementsByClass("featured-image").size() > 0) {
				urlImage = elt.getElementsByClass("featured-image").first().getElementsByTag("a").first().getElementsByTag("img").attr("src");
				urlImage = "http:"+urlImage;//add prefix http
			}
			if(elt.getElementsByClass("entry-summary").size() > 0) {
				summary = elt.getElementsByClass("entry-summary").first().getElementsByTag("p").text();
				//limit the length of summary
				if(summary.length() > 120) {
					summary = summary.substring(0,119)+"...";
				}
			}
			String id = elt.attr("id");
			String date = "";
			if(elt.getElementsByTag("time").size()>0) {
				date = elt.getElementsByTag("time").first().attr("datetime");
			}
			String link = elt.getElementsByTag("header").first().getElementsByTag("h2").first().getElementsByTag("a").first().absUrl("href");
			Map<String,String> mp = new HashMap<String,String>();
			mp.put("title", title);
			mp.put("image", urlImage);
			mp.put("summary", summary);
			mp.put("id", id);
			mp.put("date", date);
			mp.put("link", link);
			listTopics.add(mp);
		}
		return listTopics;
	}
	
	public String getNextUrl() {
		//because there is a blank space in the class, so use the method select
		Element elt = doc.select("div[class=span6 next-post]").first().getElementsByTag("a").first();
		if(elt == null) {
			return null;
		} else {
			return elt.absUrl("href");
		}
	}

}
